package com.sg.zhui.visitor.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.core.lib.utils.CallBack;
import com.core.lib.utils.ImageCompressUtils;
import com.core.lib.utils.main.ImageUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.BufferProgressDialog;
import com.sg.zhui.visitor.R;
import com.sg.zhui.visitor.config.PreferencesHelper;
import com.sg.zhui.visitor.http.AsyncRequest;
import com.sg.zhui.visitor.http.BaseStringCallback_Host;
import com.sg.zhui.visitor.http.BaseStringCallback_Host_Two;
import com.sg.zhui.visitor.http.BaseStringCallback_Host_VisitApply;
import com.sg.zhui.visitor.http.Setting;
import com.sg.zhui.visitor.http.httpContxt;
import com.sg.zhui.visitor.permission.PermissionUtil_Visitor;
import com.sg.zhui.visitor.permission.callback.PermissionResultCallBack_Visitor;
import com.sg.zhui.visitor.utils.DateDistance;
import com.sg.zhui.visitor.utils.DialogUtil_VIsitor;
import com.sg.zhui.visitor.utils.SdLocal;
import com.sg.zhui.visitor.utils.StringUtil;
import com.sg.zhui.visitor.utils.TelNumMatch;
import com.sg.zhui.visitor.utils.UploadMenuImage_Visitor;
import com.sg.zhui.visitor.utils.clip.ClipImageActivity_Visitor;
import com.sg.zhui.visitor.utils.flyn.Eyes_Visitor;
import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import butterknife.BindView;
//import butterknife.ButterKnife;
//import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;
//import top.zibin.luban.Luban;
//import top.zibin.luban.OnCompressListener;

/**
 * Created by chenlipeng on 2018/7/11 0011
 * describe:  进门申请
 */
public class IntoDoorApplyingForActivityTwo extends AppCompatActivity implements AsyncRequest {
    private RelativeLayout mRl_title_bg;
    private LinearLayout mTopbarLeftLinearLayout;
    private ImageView mTopbarLeftBackImageView;
    private TextView mTopbarLeftBackTitle;
    private TextView mTv_titlebar_title_visitor;
    private LinearLayout mRightLayout;
    private ImageButton mTopbarRightImageButton;
    private TextView mTopbarRightTextView;
    private RelativeLayout mRl_face_recognition;
    private ImageView mIv_pic;
    private ImageView ivShowPic;
    private EditText mEt_staff_phone_num;
    private EditText mEt_my_name;
    private TextView mEt_my_phone_num;
    private RelativeLayout mRl_choose_time;
    private TextView mTv_time;
    private TextView mTv_car_num;
    private EditText mEt_car_num;
    private TextView mTv_visit_thing;
    private Button mBtn_interview;
    private Button mBtn_work;
    private Button mBtn_deliver_goods;
    private Button mBtn_else;
    private RelativeLayout mRl_else_thing_case;
    private EditText mEt_else_thing_case;
    private Button mBtn_edit;


    private String currentChooseVisitType = "面试";
    private String token = "";
    //    拍照相关的

    private File compressFile;
    private Dialog mBaseDialog;

    private static final int VISITOR_APPLY = 1;
    private static final int UPLOAD_PHOTO = 2;

    private static final int VISITOR_APPLY_HANDLER = 3;
    private static final int UPLOAD_PHOTO_HANDLER = 4;
    private String mTempImagePath = "";
    private PreferencesHelper preferencesHelper;
    //    private Bitmap bitmap = null;
    private String userSid;
    private String loginPhoneNum;
    private Bitmap yetCompressBitmap;
    private BufferProgressDialog mProfressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_into_door_applying_for_two);
        bindViews();

        Eyes_Visitor.setStatusBarColor(IntoDoorApplyingForActivityTwo.this, Color.parseColor("#70A0EC"));  //translucent 透明的

        mTv_titlebar_title_visitor.setText("访客申请");
        mTopbarLeftLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        preferencesHelper = new PreferencesHelper(IntoDoorApplyingForActivityTwo.this);
        token = preferencesHelper.getToken();
        userSid = preferencesHelper.getUserSid();
        loginPhoneNum = preferencesHelper.getLoginPhoneNum();
//        token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJqd3QiLCJpYXQiOjE1MzQ5MDYyOTMsInN1YiI6IntcImNhcmROb1wiOlwiNjc4MTAwNzg1XCIsXCJuaWNrTmFtZVwiOlwi56eD5aS0XCIsXCJyb2xlVHlwZVwiOlwidmlzaXRvclwiLFwic2lkXCI6XCI4MDAwNDQzZmYxNzE0NGMxOWJiNmQ5YTk4NjllNDhiOVwiLFwidXNlck5hbWVcIjpcIjE4MjEwMTgyNDYyXCIsXCJ1c2VyVGVsXCI6XCIxODIxMDE4MjQ2MlwifSIsImV4cCI6MTUzNTMzODI5M30.8K56xRJH5f_9BG1iNCBRXqaEoNi_382yFsZRz9KFw6Q";
//        loginPhoneNum="13888888888";
//        if (TextUtils.isEmpty(userSid)) {
//            userSid = "sdfdsfeeesdfs";
//        }
        Log.e("token", "IntoDoorApplyingForActivityTwo:" + this.token);
        Log.e("token", "userSid:" + this.userSid);
        Log.e("token", "loginPhoneNum:" + this.loginPhoneNum);

        Log.e("visitor版本", "visitor版本2222222:" + httpContxt.CURRENT_PLUGIN_CODE);


        //保存图片到本地，从本地拿到
//        String picpath = SdLocal.getUserPath(IntoDoorApplyingForActivityTwo.this, userSid);
//        Bitmap bitmap = ImageUtilBase.getBitmap(picpath);
//
//        if (bitmap != null) {
//            ivShowPic.setImageBitmap(bitmap);
//            ivShowPic.setVisibility(View.VISIBLE);
//        }

        if (!TextUtils.isEmpty(loginPhoneNum)) {//设置登录的手机号码到控件上
            mEt_my_phone_num.setText(loginPhoneNum);
        }

    }

    private void bindViews() {
        mRl_title_bg = (RelativeLayout) findViewById(R.id.rl_title_bg);
        mTopbarLeftLinearLayout = (LinearLayout) findViewById(R.id.topbarLeftLinearLayout);
        mTopbarLeftBackImageView = (ImageView) findViewById(R.id.topbarLeftBackImageView);
        mTopbarLeftBackTitle = (TextView) findViewById(R.id.topbarLeftBackTitle);
        mTv_titlebar_title_visitor = (TextView) findViewById(R.id.tv_titlebar_title_visitor);
        mRightLayout = (LinearLayout) findViewById(R.id.rightLayout);
        mTopbarRightImageButton = (ImageButton) findViewById(R.id.topbarRightImageButton);
        mTopbarRightTextView = (TextView) findViewById(R.id.topbarRightTextView);
        mRl_face_recognition = (RelativeLayout) findViewById(R.id.rl_face_recognition);
        mIv_pic = (ImageView) findViewById(R.id.iv_pic);
        ivShowPic = (ImageView) findViewById(R.id.iv_show_pic);
        mEt_staff_phone_num = (EditText) findViewById(R.id.et_staff_phone_num);
        mEt_my_name = (EditText) findViewById(R.id.et_my_name);
        mEt_my_phone_num = (TextView) findViewById(R.id.et_my_phone_num);
        mRl_choose_time = (RelativeLayout) findViewById(R.id.rl_choose_time);
        mTv_time = (TextView) findViewById(R.id.tv_time);
        mTv_car_num = (TextView) findViewById(R.id.tv_car_num);
        mEt_car_num = (EditText) findViewById(R.id.et_car_num);
        mTv_visit_thing = (TextView) findViewById(R.id.tv_visit_thing);
        mBtn_interview = (Button) findViewById(R.id.btn_interview);
        mBtn_work = (Button) findViewById(R.id.btn_work);
        mBtn_deliver_goods = (Button) findViewById(R.id.btn_deliver_goods);
        mBtn_else = (Button) findViewById(R.id.btn_else);
        mRl_else_thing_case = (RelativeLayout) findViewById(R.id.rl_else_thing_case);
        mEt_else_thing_case = (EditText) findViewById(R.id.et_else_thing_case);
        mBtn_edit = (Button) findViewById(R.id.btn_edit);

        final int blueColor = getResources().getColor(R.color.main_color_visitor);

        mEt_car_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

//                Log.e("数据", editable.toString());
                String s = editable.toString().toUpperCase();
//                Log.e("数据", s);

                if (!editable.toString().equals(s)) {
                    mEt_car_num.setText(s);
                    mEt_car_num.setSelection(mEt_car_num.getText().toString().length());
                }
            }
        });

        mBtn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String etStaffPhoneNumStr = mEt_staff_phone_num.getText().toString().trim();
                if (!CheckPhoneNum(etStaffPhoneNumStr)) {
                    return;
                }

                String myName = mEt_my_name.getText().toString().trim();
                if (TextUtils.isEmpty(myName)) {
                    Toast.makeText(IntoDoorApplyingForActivityTwo.this, "申请者名字不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                String etMyPhoneNumStr = mEt_my_phone_num.getText().toString().trim();
                if (!CheckPhoneNum(etMyPhoneNumStr)) {
                    return;
                }

                if (TextUtils.isEmpty(mTv_time.getText().toString().trim())) {
                    Toast.makeText(IntoDoorApplyingForActivityTwo.this, "访问日期不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                visitorApply();
            }
        });
        mBtn_interview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBtn_interview.setBackgroundColor(blueColor);
                mBtn_work.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_deliver_goods.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_else.setBackgroundColor(Color.parseColor("#e3e3e3"));

                mBtn_interview.setTextColor(getResources().getColor(R.color.white_color));
                mBtn_work.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_deliver_goods.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_else.setTextColor(Color.parseColor("#aaa3a1"));

                currentChooseVisitType = "面试";
                mRl_else_thing_case.setVisibility(View.GONE);
                mEt_else_thing_case.setText("");
            }
        });

        mBtn_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBtn_interview.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_work.setBackgroundColor(blueColor);
                mBtn_deliver_goods.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_else.setBackgroundColor(Color.parseColor("#e3e3e3"));

                mBtn_interview.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_work.setTextColor(getResources().getColor(R.color.white_color));
                mBtn_deliver_goods.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_else.setTextColor(Color.parseColor("#aaa3a1"));

                currentChooseVisitType = "办公";
                mRl_else_thing_case.setVisibility(View.GONE);
                mEt_else_thing_case.setText("");
            }
        });

        mBtn_deliver_goods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBtn_interview.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_work.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_deliver_goods.setBackgroundColor(blueColor);
                mBtn_else.setBackgroundColor(Color.parseColor("#e3e3e3"));

                mBtn_interview.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_work.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_deliver_goods.setTextColor(getResources().getColor(R.color.white_color));
                mBtn_else.setTextColor(Color.parseColor("#aaa3a1"));

                currentChooseVisitType = "送货";
                mRl_else_thing_case.setVisibility(View.GONE);
                mEt_else_thing_case.setText("");
            }
        });
        mBtn_else.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBtn_interview.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_work.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_deliver_goods.setBackgroundColor(Color.parseColor("#e3e3e3"));
                mBtn_else.setBackgroundColor(blueColor);

                mBtn_interview.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_work.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_deliver_goods.setTextColor(Color.parseColor("#aaa3a1"));
                mBtn_else.setTextColor(getResources().getColor(R.color.white_color));

                currentChooseVisitType = "其他";
                mRl_else_thing_case.setVisibility(View.VISIBLE);
                mEt_else_thing_case.setText("");
            }
        });

        mRl_choose_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseTime(mTv_time);
            }
        });

        mRl_face_recognition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogPic();
            }
        });
//        mTopbarRightTextView.setVisibility(View.GONE);
        mTopbarRightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent(IntoDoorApplyingForActivityTwo.this, ApplyForAndAccreditRecordActivity.class);
                startActivity(intent1);
            }
        });
    }

    private boolean CheckPhoneNum(String phoneNum) {
        if (TextUtils.isEmpty(phoneNum)) {
            Toast.makeText(IntoDoorApplyingForActivityTwo.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (phoneNum.length() != 11) {
            Toast.makeText(IntoDoorApplyingForActivityTwo.this, "手机号位数不是11位", Toast.LENGTH_SHORT).show();
            return false;
        }

        Boolean myMobileNO = TelNumMatch.isMobileNO(phoneNum);
        if (!myMobileNO) {
            Toast.makeText(IntoDoorApplyingForActivityTwo.this, "请输入有效的手机号", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 访客头像上传
     */
    public void uploadPhoto() {
        if (StringUtil.isEmpty(token)) {
            return;
        }

        String url = Setting.uploadPhoto();
        if (null == compressFile) {
            return;
        }

        OkHttpUtils
                .post()
                .addFile("file", compressFile.getName(), compressFile)
                .url(url)
                .id(UPLOAD_PHOTO)
                .addHeader("Auth-Token", token)
                .build()
                .execute(new BaseStringCallback_Host_Two(IntoDoorApplyingForActivityTwo.this, this));
    }


    /**
     * 访客申请
     */
    public void visitorApply() {

        String url = Setting.visitorApply();

        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("employeeTel", mEt_staff_phone_num.getText().toString().trim());
        stringStringHashMap.put("visitorName", mEt_my_name.getText().toString().trim());
        stringStringHashMap.put("visitTime", mTv_time.getText().toString().trim());
        stringStringHashMap.put("visitorTel", mEt_my_phone_num.getText().toString().trim());

        String etCarNumStr = mEt_car_num.getText().toString().trim();
        if (!StringUtil.isEmpty(etCarNumStr)) {

            boolean b = checkPlateNumberFormat(etCarNumStr);
            if (b) {
                stringStringHashMap.put("carNo", etCarNumStr);
            } else {
                Toast.makeText(this, "车牌号不符合规则", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        if (currentChooseVisitType.equals("其他")) {

            String elseThingCaseStr = mEt_else_thing_case.getText().toString();
            if (!TextUtils.isEmpty(elseThingCaseStr)) {
                stringStringHashMap.put("reason", elseThingCaseStr);
            } else {
                Toast.makeText(this, "请输入访问事由", Toast.LENGTH_SHORT).show();
                return;
            }

        } else {
            stringStringHashMap.put("reason", currentChooseVisitType);
        }

        if (StringUtil.isEmpty(token)) {
            Toast.makeText(this, "token为空", Toast.LENGTH_SHORT).show();
            return;
        }

        OkHttpUtils
                .post().params(stringStringHashMap)
                .url(url)
                .id(VISITOR_APPLY)
                .addHeader("Auth-Token", token)
                .build()
                .execute(new BaseStringCallback_Host_VisitApply(IntoDoorApplyingForActivityTwo.this, IntoDoorApplyingForActivityTwo.this));
    }

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 3:
                    String data = (String) msg.obj;
                    if (null != data) {
                        try {
//                            返回提示信息有三种：
//                            1、该时间段已经提交过申请，不能重复提交
//                            2、未找到此员工手机号，请重新输入！
//                            3、申请成功！

//                            {
//                                "code" : 1002,
//                                    "msg" : "未找到此员工手机号，请重新输入！",
//                                    "data" : null
//                            }

                            JSONObject jsonObject = new JSONObject(data);
                            String msg1 = jsonObject.getString("msg");
                            Toast.makeText(IntoDoorApplyingForActivityTwo.this, msg1, Toast.LENGTH_SHORT).show();

                            if (null != msg1 && msg1.contains("申请成功")) {
                                finish();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case 4://上传头像成功的回调
                    String data3 = (String) msg.obj;
                    if (null != data3) {
                        try {
//                                "code" : 1002,
//                                    "msg" : "上传失败",
//                                    "data" : null
                            JSONObject jsonObject = new JSONObject(data3);
                            String code = jsonObject.getString("code");
//                            String msg1 = jsonObject.getString("msg");
                            if (code.equals("1002")) {//上传失败

                                Toast.makeText(IntoDoorApplyingForActivityTwo.this, "上传头像失败", Toast.LENGTH_SHORT).show();
                                ivShowPic.setVisibility(View.GONE);


                            } else if (code.equals("1000")) {//上传成功
                                JSONObject data1 = (JSONObject) jsonObject.get("data");
                                String headUrl = data1.getString("url");

                                if (!StringUtil.isEmpty(headUrl)) {

                                    //保存图片到本地，从本地拿到
                                    String picpath = SdLocal.getUserPath(IntoDoorApplyingForActivityTwo.this, userSid);
                                    ImageUtilBase.saveImageToSd(yetCompressBitmap, picpath);

                                    Toast.makeText(IntoDoorApplyingForActivityTwo.this, "上传头像成功", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(IntoDoorApplyingForActivityTwo.this, "上传头像失败", Toast.LENGTH_SHORT).show();
                                    ivShowPic.setVisibility(View.GONE);

//                                    String picpath = SdLocal.getUserPath(IntoDoorApplyingForActivityTwo.this, userSid);
//                                    ImageUtilBase.saveImageToSd(yetCompressBitmap, picpath);
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                default:
                    break;
            }
        }

    };

    @Override
    public void RequestComplete(Object object, Object data) {
        Log.e("数据RequestComplete", data.toString());
        String result = (String) data;

        if (object.equals(VISITOR_APPLY)) {
            Message msg = mHandler.obtainMessage();
            msg.what = VISITOR_APPLY_HANDLER;
            msg.obj = result;
            mHandler.sendMessage(msg);

        } else {//这个代表是 上传头像成功的回调
            Message msg = mHandler.obtainMessage();
            msg.what = UPLOAD_PHOTO_HANDLER;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
//        {
//            "code" :1001,
//                "msg" :"http://114.115.140.117:9090/qrcode/generateCodeToFront?cardNo=1367918344",
//                "data" :null
//        }
    }

    @Override
    public void RequestError(Object object, int errorId, final String errorMessage) {
        Log.e("数据RequestError", errorMessage + "");

        if (object.equals(UPLOAD_PHOTO)) {
            ((Activity) IntoDoorApplyingForActivityTwo.this).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //此时已在主线程中，可以更新UI了
                    Toast.makeText(IntoDoorApplyingForActivityTwo.this, errorMessage + "", Toast.LENGTH_SHORT).show();
                    ivShowPic.setVisibility(View.GONE);
                }
            });
        } else {
            ((Activity) IntoDoorApplyingForActivityTwo.this).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //此时已在主线程中，可以更新UI了
                    Toast.makeText(IntoDoorApplyingForActivityTwo.this, errorMessage + "", Toast.LENGTH_SHORT).show();
//                //保存图片到本地，从本地拿到
//                String picpath = SdLocal.getUserPath(IntoDoorApplyingForActivityTwo.this, userSid);
//                ImageUtilBase.saveImageToSd(yetCompressBitmap, picpath);
                }
            });
        }

    }

    /**
     * 选择时间
     *
     * @param xuanze_shijian
     */
    private void chooseTime(final TextView xuanze_shijian) {
        Calendar calendar = Calendar.getInstance();
//              获得当前时间的月份，月份从0开始所以结果要加1
        final int month = calendar.get(Calendar.MONTH) + 1;
        final int DATE = calendar.get(Calendar.DATE);

        final String currentYear = getCurrentYear();
        String RangeEnd = currentYear + 1;

        final DatePicker picker = new DatePicker(IntoDoorApplyingForActivityTwo.this);
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setTopPadding(ConvertUtils.toPx(IntoDoorApplyingForActivityTwo.this, 10));
        picker.setRangeStart(2000, 8, 29);
        picker.setRangeEnd(2100, month, DATE);
        picker.setSelectedItem(Integer.parseInt(currentYear), month, DATE);
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String chooseyear, String chooseMonth, String chooseDay) {
                String currentMonth = null;
                if (month < 10) {
                    currentMonth = "0" + month;
                } else {
                    currentMonth = month + "";
                }

                String currentDay = null;
                if (DATE < 10) {
                    currentDay = "0" + DATE;
                } else {
                    currentDay = DATE + "";
                }

                String currentTime = currentYear + "-" + currentMonth + "-" + currentDay;
                String chooseTime = chooseyear + "-" + chooseMonth + "-" + chooseDay;

                if (Integer.parseInt(chooseyear) == Integer.parseInt(currentYear)) {

                    String distanceTime = DateDistance.getDistanceTime(currentTime, chooseTime);
                    Log.e("distanceTime", distanceTime);

                    if (Integer.parseInt(distanceTime) <= 3) {
                        xuanze_shijian.setText(chooseTime);
                    } else {
                        Toast.makeText(IntoDoorApplyingForActivityTwo.this, "时间不符合要求", Toast.LENGTH_SHORT).show();
                        xuanze_shijian.setText("");
                    }


                } else {
                    Toast.makeText(IntoDoorApplyingForActivityTwo.this, "时间不符合要求", Toast.LENGTH_SHORT).show();
                    xuanze_shijian.setText("");
                }


            }
        });
        picker.setCancelVisible(false);
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
//                xuanze_shijian.setText(year + "年" + picker.getSelectedMonth() + "月" + picker.getSelectedDay() + "日");
            }

            @Override
            public void onMonthWheeled(int index, String month) {
//                xuanze_shijian.setText(picker.getSelectedYear() + "年" + month + "月" + picker.getSelectedDay() + "日");
            }

            @Override
            public void onDayWheeled(int index, String day) {
//                xuanze_shijian.setText(picker.getSelectedYear() + "年" + picker.getSelectedMonth() + "月" + day + "日");
            }
        });
        picker.show();
    }

    public String getCurrentYear() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

        Date d = new Date();
        String t = sdf.format(d);
        String y = t.substring(0, 4);
        return y;
    }

    /**
     * 弹框
     */
    private void DialogPic() {
        PermissionUtil_Visitor.getInstance().request(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,},
                new PermissionResultCallBack_Visitor() {
                    @Override
                    public void onPermissionGranted() {
                        //
                        closeSoftInput(IntoDoorApplyingForActivityTwo.this);
                        String temp = SdLocal.getTempPhotoPath(IntoDoorApplyingForActivityTwo.this, "temp_camera_icon");
                        UploadMenuImage_Visitor.getInstance(IntoDoorApplyingForActivityTwo.this).setFilePath(temp);
                        UploadMenuImage_Visitor.getInstance(IntoDoorApplyingForActivityTwo.this).setIsCut(true);
                        UploadMenuImage_Visitor.getInstance(IntoDoorApplyingForActivityTwo.this).setIsPhotoDouble(false);
                        UploadMenuImage_Visitor.getInstance(IntoDoorApplyingForActivityTwo.this).showPopAddPhoto();
                    }

                    @Override
                    public void onPermissionGranted(String... permissions) {
                        if (permissions == null || permissions.length == 0) {
                        }
                    }

                    @Override
                    public void onPermissionDenied(String... permissions) {
                        if (permissions != null) {

                        }
                    }

                    @Override
                    public void onRationalShow(String... permissions) {
                        if (permissions != null) {
                            UIHelper.showToast(IntoDoorApplyingForActivityTwo.this, R.string.permission_tip_visitor);
                            PermissionUtil_Visitor.openSettingActivity(IntoDoorApplyingForActivityTwo.this);
                        }
                    }
                });
    }

    private void modifyAvatar(final String cropImagePath) {
        Bitmap waitCompressBitmap = null;
        try {
            waitCompressBitmap = ImageCompressUtils.getimage(cropImagePath);//得到要压缩的图片

            yetCompressBitmap = ImageCompressUtils.compressImage(waitCompressBitmap);//压缩图片

            if (yetCompressBitmap != null) {
                ivShowPic.setImageBitmap(yetCompressBitmap);
                ivShowPic.setVisibility(View.VISIBLE);

                String sdCardDir = Environment.getExternalStorageDirectory() + "/myHeadImage/";
                File dirFile = new File(sdCardDir);  //目录转化成文件夹
                if (!dirFile.exists()) {                //如果不存在，那就建立这个文件夹
                    dirFile.mkdirs();
                }                            //文件夹有啦，就可以保存图片啦
                compressFile = new File(sdCardDir, System.currentTimeMillis() + ".jpg");// 在SDcard的目录下创建图片文,以当前时间为其命名
                ImageCompressUtils.saveBitmap(yetCompressBitmap, compressFile.getPath());

                uploadPhoto();
            } else {
                Toast.makeText(IntoDoorApplyingForActivityTwo.this, "压缩图片失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //上传头像更新UI
        UploadMenuImage_Visitor.getInstance(IntoDoorApplyingForActivityTwo.this).onActivityResult(new CallBack() {
            @Override
            public void callBackSuccess(Object obj) {
                super.callBackSuccess(obj);

                mTempImagePath = (String) obj;
                loadImage();

            }
        }, requestCode, resultCode, data);
    }

    private void loadImage() {
        if (!TextUtils.isEmpty(mTempImagePath)) {
            modifyAvatar(mTempImagePath);
        }
    }

    public static void closeSoftInput(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null && view.getWindowToken() != null) {
            @SuppressLint("WrongConstant") InputMethodManager imm = (InputMethodManager) activity.getSystemService("input_method");
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }

    }

    public void showProgressDialog() {
        if (this.mProfressDialog == null) {
            this.mProfressDialog = new BufferProgressDialog(this, false);
        }

    }


    public void hideProgressDialog() {
        if (this.mProfressDialog != null) {
            this.mProfressDialog.destroyProgressDialog();
            this.mProfressDialog = null;
        }

    }

//    public void hideLoadingDialog() {
//        if (mBaseDialog != null && mBaseDialog.isShowing()) {
//            mBaseDialog.dismiss();
//        }
//    }
//
//    public void showLoadingDialog(String msg) {
//        if (msg != null) {
//            if (mBaseDialog != null && mBaseDialog.isShowing()) {
//                mBaseDialog.dismiss();
//                mBaseDialog = null;
//            }
//            mBaseDialog = DialogUtil_VIsitor.showLoading(msg, IntoDoorApplyingForActivityTwo.this);
//        }
//    }

    public boolean checkPlateNumberFormat(String content) {
        String pattern = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}(([A-HJ-Z]{1}[A-HJ-NP-Z0-9]{5})|([A-HJ-Z]{1}(([DF]{1}[A-HJ-NP-Z0-9]{1}[0-9]{4})|([0-9]{5}[DF]{1})))|([A-HJ-Z]{1}[A-D0-9]{1}[0-9]{3}警)))|([0-9]{6}使)|((([沪粤川云桂鄂陕蒙藏黑辽渝]{1}A)|鲁B|闽D|蒙E|蒙H)[0-9]{4}领)|(WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼·•]{1}[0-9]{4}[TDSHBXJ0-9]{1})|([VKHBSLJNGCE]{1}[A-DJ-PR-TVY]{1}[0-9]{5})";
        return Pattern.matches(pattern, content);
    }
}
//        Luban.with(this)
//                .load(new File(cropImagePath))                     //传人要压缩的图片
//                .setCompressListener(new OnCompressListener() {
//                    @Override
//                    public void onStart() {
//                        //  压缩开始前调用，可以在方法内启动 loading UI
//                    }
//
//                    @Override
//                    public void onSuccess(File file) {
//
//                        //  压缩成功后调用，返回压缩后的图片文件
//                        compressFile = file;
//                        bitmap = ImageUtilBase.getBitmap(cropImagePath);
//                        if (bitmap != null) {
//                            ivShowPic.setImageBitmap(bitmap);
//
//                            ivShowPic.setVisibility(View.VISIBLE);
//
//                            uploadPhoto();
//                        }
//                      /*  Glide.with(IntoDoorApplyingForActivityTwo.this).load(photoPath)
//                                .asBitmap().dontAnimate().fitCenter()
//                                .into(ivShowPic);*/
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        //  当压缩过程出现问题时调用
//                    }
//                }).launch();    //启动压缩


//        token = BeanManager.getBean().getUserId();

/**
 * 验证验证输入汉字
 *
 * @param str
 * @return 如果是符合格式的字符串, 返回 <b>true </b>,否则为 <b>false </b>
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 * <p>
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 * @param context
 * @param uri
 * @return the file path or null
 */
//    public static boolean IsChinese(String str) {
//        String regex = "^[\u4e00-\u9fa5],{0,}$";
//        return match(regex, str);
//    }

/**
 * @param regex 正则表达式字符串
 * @param str   要匹配的字符串
 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
 */
//    private static boolean match(String regex, String str) {
//        Pattern pattern = Pattern.compile(regex);
//        Matcher matcher = pattern.matcher(str);
//        return matcher.matches();
//    }

/**
 * 根据Uri返回文件绝对路径
 * 兼容了file:///开头的 和 content://开头的情况
 *
 * @param context
 * @param uri
 * @return the file path or null
 */
//    public String getRealFilePathFromUri(final Context context, final Uri uri) {
//        if (null == uri) return null;
//        final String scheme = uri.getScheme();
//        String data = null;
//        if (scheme == null)
//            data = uri.getPath();
//        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
//            data = uri.getPath();
//        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
//            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
//            if (null != cursor) {
//                if (cursor.moveToFirst()) {
//                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//                    if (index > -1) {
//                        data = cursor.getString(index);
//                    }
//                }
//                cursor.close();
//            }
//        }
//        return data;
//    }

//    /**
//     * 是否是汉字的正则
//     */
//    private String regexIsHanZi = "[\\u4e00-\\u9fa5]+";
//
//    public static boolean matchRegular(String str, String reg) {
//        Pattern pattern = Pattern.compile(reg);
//        Matcher matcher = pattern.matcher(str);
//        return matcher.matches();
//    }


//拍照回调
//        if (requestCode == REQUEST_CODE_TAKE_PHOTO && resultCode == RESULT_OK) {
//                if (takePhotoFile != null) {
//                photoPath = takePhotoFile.getAbsolutePath();
//
////                gotoClipActivity(Uri.fromFile(takePhotoFile));
//                modifyAvatar();
//                // 对图片进行裁剪
//
//                }
//                }
//
//                //选择图片回调
//                if (requestCode == REQUEST_CODE_CHOICE_PHOTO && resultCode == RESULT_OK) {
//                try {
//                photoPath = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
//
////                gotoClipActivity(Uri.parse(photoPath));
//                modifyAvatar();
//                // 对图片进行裁剪
//                } catch (Exception e) {
//                e.printStackTrace();
//                }
//                }
//
//                //裁剪
//                if (requestCode == REQUEST_CROP_PHOTO && resultCode == RESULT_OK) {
//final Uri uri = data.getData();
//        if (uri == null) {
//        return;
//        }
//        }
